import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import {
    ProForm,
    ProFormText,
    ProFormSelect,
    ProFormTextArea,
    ProFormGroup,
    ProFormDatePicker,
    ProFormSwitch,
    ProFormItem
} from '@ant-design/pro-components';
import { Button, Input, Modal } from 'antd';
import Cron from "qnn-react-cron";

import { QiniuFileUpload } from '../../../../components';
import { getNowFormatDate, uuid } from '../../../../utils';
import { FLOW_PROJECT_TYPE_SELECT_OPTIONS, flowCreateEmptyFile, flowSaveProject, flowUpdateProject, MetaDataDomain, metaDataSaveDomain, metaDataUpdateDomain } from '../../../../services';
import { dsFind, dsInsert, dsUpdate, dsUpdateById, schedulerCreateEmptyTaskTemplate, Task, TaskTemplate } from '@/services/local';
import { SCHEDULER_TASK_CLASS_IDENTIFIER, SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER } from '@/services/constants';

export interface TaskEditorProps {
    style?: CSSProperties;
    item?: Task;
    onFinish: () => Promise<void> | void;
}

export const TaskEditor: React.FC<TaskEditorProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [cronValue, setCronValue] = useState('');

    const [cronShown, setCronShown] = useState<boolean>(false);

    const [templates, setTemplates] = useState<Array<TaskTemplate>>([]);

    let cronRef;

    const requestCallback = useCallback(async () => {
        console.log('---------', props.item);
        if (!props.item) return {};
        setCronValue(props.item?.cron);
        return props.item;
    }, [props.item]);

    useEffect(() => {
        dsFind(0, SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER, {}).then(({ data }) => {
            setTemplates(data);
        })
    }, [])

    return (
        <Container>
            <ProForm<Task>
                initialValues={props.item}
                request={requestCallback}
                onFinish={async (values) => {
                    //TODO 校验
                    let start_str = values.start_time;
                    let end_str = values.end_time;

                    values = {
                        ...props.item,
                        ...values,
                        cron: cronValue,
                        enable: !!values.enable,
                        start_time: parseInt(start_str.replaceAll("-", '')),
                        end_time: end_str && end_str != '' ? parseInt(start_str.replaceAll("-", '')) : undefined,
                    };

                    if (props.item) {
                        //编辑
                        let _ = await dsUpdateById(0, SCHEDULER_TASK_CLASS_IDENTIFIER, props.item.id, values);
                        // let _ = await flowUpdateProject(values);
                    } else {
                        //添加 
                        console.log(values);
                        values.identifier = uuid();
                        let _ = await dsInsert(0, SCHEDULER_TASK_CLASS_IDENTIFIER, values);
                    }
                    await props.onFinish();
                }}
                submitter={false}
            >
                <ProFormGroup>
                    <ProFormText
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="title"
                        label="名称" />

                    <ProFormSelect
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        options={templates.map((item) => {
                            return {
                                value: item.identifier,
                                label: item.title || item.name,
                            }
                        })}
                        name="template_identifier"
                        label="任务模板" />
                </ProFormGroup>
                <ProFormGroup>
                    <ProFormSwitch
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="enable"
                        label="是否启用" />
                    <ProFormDatePicker
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="start_time"
                        label="开始时间" />
                    <ProFormDatePicker
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="end_time"
                        label="结束时间" />
                </ProFormGroup>
                <ProFormItem label="任务周期" name="cronValue">
                    {
                        !!cronShown ? (<>
                            <Input disabled value={cronValue} addonAfter={
                                <Button
                                    type='primary'
                                    style={{ margin: '-1px -12px', border: 'none' }}
                                    onClick={() => {
                                        setCronValue(cronRef.getValue());
                                        setCronShown(false);
                                    }}>生成</Button>
                            } />
                            <Cron
                                value={cronValue}
                                getCronFns={fns => cronRef = fns}
                                // getCronFns={setCronRef}
                                footer={[]}
                            ></Cron>
                        </>) : (<>
                            <Input disabled value={cronValue} addonAfter={
                                <Button
                                    type='primary'
                                    style={{ margin: '-1px -12px', border: 'none' }}
                                    onClick={() => {
                                        setCronShown(true);
                                    }}>设置周期</Button>
                            } />
                        </>)
                    }
                </ProFormItem>

                <ProFormGroup>
                    <ProFormText
                        rules={[]}
                        fieldProps={{}}
                        name="times"
                        label="执行次数" />
                    <ProFormText
                        rules={[]}
                        fieldProps={{}}
                        name="try_times"
                        label="失败尝试次数" />
                    <ProFormText
                        rules={[]}
                        fieldProps={{}}
                        name="timeout"
                        label="超时时间" />
                </ProFormGroup>
                <ProFormTextArea
                    rules={[]}
                    fieldProps={{}}
                    name="variables"
                    label="变量" />
                <ProFormTextArea
                    width="xl"
                    fieldProps={{}}
                    name="description"
                    label="描述" />
                <ProFormItem>
                    <Button loading={loading} type="primary" htmlType="submit">
                        添加
                    </Button>
                </ProFormItem>
            </ProForm>
            <Modal
                styles={{
                    content: {
                        minWidth: '600px',
                        minHeight: '400px'
                    }
                }}
                title="添加数据流"
                footer={false}
                destroyOnClose={true}
                open={isModalOpen}
                onOk={async () => {
                    //刷新
                    // await refresh(page, pageSize);
                    setIsModalOpen(false);
                }} onCancel={async () => {
                    //刷新
                    // await refresh(page, pageSize);
                    setIsModalOpen(false);
                }}>
                <Cron
                    value={cronValue}
                    onOk={setCronValue}
                />
            </Modal>
        </Container>
    );
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
`;